package com.mohe.dangjian.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;

import com.mohe.dangjian.model.CommunityGeneralParty;
import com.mohe.dangjian.model.CommunityParty;
import com.mohe.dangjian.model.PartyActivity;
import com.mohe.dangjian.service.interfaces.ICommunityGeneralParty;
import com.mohe.dangjian.service.interfaces.ICommunityParty;
import com.mohe.dangjian.service.interfaces.IPartyActivity;
import com.mohe.dangjian.utils.ExcelException;
import com.mohe.dangjian.utils.ExcelPartyActivity;
import com.mohe.dangjian.utils.ExcelUtil;
import com.mohe.dangjian.utils.Json;
import com.mohe.dangjian.utils.JsonUtil;
import com.mohe.dangjian.utils.Page;
import com.mohe.dangjian.utils.RegExHtmlUtils;
import com.opensymphony.xwork2.ActionSupport;

/**
 * 居民区党建动态Action
 * 
 * @author wxm
 * 
 */
public class CommunityPartyActivityAction extends ActionSupport {

	private static final long serialVersionUID = 9009232964113393765L;
	private static final String partyType = "居民区";

	private IPartyActivity partyActivityServ;
	private ICommunityParty communityPartyServ;
	private ICommunityGeneralParty communityGeneralPartyServ;
	
	private List<PartyActivity> partyActivityList;
	private List<CommunityParty> communityPartyList;
	private List<CommunityGeneralParty> communityGeneralPartyList;
	private Page page = new Page();
	private PartyActivity partyActivity = new PartyActivity();

	// 页面提示消息
	private String flag;
	// 表示从哪跳转到编辑页面，1:主页面/2:查看页面
	private Integer editFrom;
	// 上传的图片
	private List<File> image; 
	// 图片名称
	private List<String> imageFileName; 
	// 党组织名称
	private String partyName;
	// 党建动态名称
	private String activityName;
	// 党建动态类型
	private String activityType;
	// 党建动态日期
	private String activityDate;
	// 党建动态地址
	private String address;
	// 党建动态参加人数
	private Integer attendNum;
	// 党建动态内容
	private String content;
	// 党建动态情况
	private String situation;
	// 党建动态ID
	private Long timeKey;
	// 党建动态图片展示
	private List<String> picList;
	// 从其他页面跳转过来URL中参数
	private String partyNameParam;

	public IPartyActivity getPartyActivityServ() {
		return partyActivityServ;
	}

	public void setPartyActivityServ(IPartyActivity partyActivityServ) {
		this.partyActivityServ = partyActivityServ;
	}

	public ICommunityParty getCommunityPartyServ() {
		return communityPartyServ;
	}

	public void setCommunityPartyServ(ICommunityParty communityPartyServ) {
		this.communityPartyServ = communityPartyServ;
	}

	public List<PartyActivity> getPartyActivityList() {
		return partyActivityList;
	}

	public void setPartyActivityList(List<PartyActivity> partyActivityList) {
		this.partyActivityList = partyActivityList;
	}

	public List<CommunityParty> getCommunityPartyList() {
		return communityPartyList;
	}

	public void setCommunityPartyList(List<CommunityParty> communityPartyList) {
		this.communityPartyList = communityPartyList;
	}

	public Page getPage() {
		return page;
	}

	public void setPage(Page page) {
		this.page = page;
	}

	public PartyActivity getPartyActivity() {
		return partyActivity;
	}

	public void setPartyActivity(PartyActivity partyActivity) {
		this.partyActivity = partyActivity;
	}

	public String getFlag() {
		return flag;
	}

	public void setFlag(String flag) {
		this.flag = flag;
	}

	public Integer getEditFrom() {
		return editFrom;
	}

	public void setEditFrom(Integer editFrom) {
		this.editFrom = editFrom;
	}
	
	public List<File> getImage() {
		return image;
	}

	public void setImage(List<File> image) {
		this.image = image;
	}

	public List<String> getImageFileName() {
		return imageFileName;
	}

	public void setImageFileName(List<String> imageFileName) {
		this.imageFileName = imageFileName;
	}

	public String getPartyName() {
		return partyName;
	}

	public void setPartyName(String partyName) {
		this.partyName = partyName;
	}

	public String getActivityName() {
		return activityName;
	}

	public void setActivityName(String activityName) {
		this.activityName = activityName;
	}

	public String getActivityType() {
		return activityType;
	}

	public void setActivityType(String activityType) {
		this.activityType = activityType;
	}

	public String getActivityDate() {
		return activityDate;
	}

	public void setActivityDate(String activityDate) {
		this.activityDate = activityDate;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	public Integer getAttendNum() {
		return attendNum;
	}

	public void setAttendNum(Integer attendNum) {
		this.attendNum = attendNum;
	}

	public String getContent() {
		return content;
	}

	public void setContent(String content) {
		this.content = content;
	}

	public String getSituation() {
		return situation;
	}

	public void setSituation(String situation) {
		this.situation = situation;
	}

	public Long getTimeKey() {
		return timeKey;
	}

	public void setTimeKey(Long timeKey) {
		this.timeKey = timeKey;
	}

	public List<String> getPicList() {
		return picList;
	}

	public void setPicList(List<String> picList) {
		this.picList = picList;
	}

	public String getPartyNameParam() {
		return partyNameParam;
	}

	public void setPartyNameParam(String partyNameParam) {
		this.partyNameParam = partyNameParam;
	}

	public ICommunityGeneralParty getCommunityGeneralPartyServ() {
		return communityGeneralPartyServ;
	}

	public void setCommunityGeneralPartyServ(
			ICommunityGeneralParty communityGeneralPartyServ) {
		this.communityGeneralPartyServ = communityGeneralPartyServ;
	}

	public List<CommunityGeneralParty> getCommunityGeneralPartyList() {
		return communityGeneralPartyList;
	}

	public void setCommunityGeneralPartyList(
			List<CommunityGeneralParty> communityGeneralPartyList) {
		this.communityGeneralPartyList = communityGeneralPartyList;
	}

	/**
	 * 获取党建动态信息列表
	 * @return
	 */
	public String getPartyActivityListForPage() {
		partyActivity.setPartyType(partyType);
		int count = partyActivityServ.getCount(partyActivity);
		page.setCount(count);
		partyActivityList = partyActivityServ.getPartyActivityList(partyActivity, page);
		// 所有党总支
		communityGeneralPartyList = communityGeneralPartyServ.getAllCommunityGeneralParty();
		// 所有党支部
		communityPartyList = communityPartyServ.getAllCommunityParty();
		return "partyActivity.jsp";
	}
	
	/**
	 * 分页
	 */
	public void searchPartyActivityList() {
		partyActivity.setPartyType(partyType);
		Json json = new Json();
		List<Map<String, String>> mapList = new ArrayList<Map<String, String>>();
		int count = partyActivityServ.getCount(partyActivity);
		page.setCount(count);
		List<PartyActivity> list = partyActivityServ.getPartyActivityList(partyActivity, page);
		if (list != null) {
			int index = (page.getCurrPage() - 1) * page.getPageSize() + 1;
			for (PartyActivity s : list) {
				Map<String, String> map = new HashMap<String, String>();
				map.put("index", index + "");
				if (s.getTimeKey() != null) {
					map.put("timeKey", s.getTimeKey() + "");
				} else {
					map.put("timeKey", "0");
				}
				if (!StringUtils.isBlank(s.getPartyName())) {
					map.put("partyName", s.getPartyName());
				} else {
					map.put("partyName", "");
				}
				if (!StringUtils.isBlank(s.getActivityName())) {
					map.put("activityName", s.getActivityName());
				} else {
					map.put("activityName", "");
				}
				if (!StringUtils.isBlank(s.getActivityType())) {
					map.put("activityType", s.getActivityType());
				} else {
					map.put("activityType", "");
				}
				if (!StringUtils.isBlank(s.getActivityDate())) {
					map.put("activityDate", s.getActivityDate());
				} else {
					map.put("activityDate", "");
				}
				if (!StringUtils.isBlank(s.getAddress())) {
					map.put("address", s.getAddress());
				} else {
					map.put("address", "");
				}
				if (s.getAttendNum() != null) {
					map.put("attendNum", s.getAttendNum().toString());
				} else {
					map.put("attendNum", "");
				}
				if (!StringUtils.isBlank(s.getContent())) {
					map.put("content", s.getContent());
				} else {
					map.put("content", "");
				}
				if (!StringUtils.isBlank(s.getSituation())) {
					map.put("situation", s.getSituation());
				} else {
					map.put("situation", "");
				}
				mapList.add(map);
				index++;
			}
		}
		json.setObject(page);
		json.setMap(mapList);
		JsonUtil.writeJson(json);
	}
	
	/**
	 * 跳转到编辑界面
	 * @return
	 */
	public String toEditPartyActivity() {
		partyActivity = partyActivityServ.getPartyActivityById(partyActivity.getTimeKey());
		communityPartyList = communityPartyServ.getAllCommunityParty();
		return "editPartyActivity.jsp";
	}
	
	/**
	 * 更新党建动态信息
	 */
	public String updatePartyActivity(){
		partyActivity = partyActivityServ.getPartyActivityById(timeKey);
		partyActivity.setPartyType(partyType);
		partyActivity.setPartyName(partyName);
		partyActivity.setActivityName(activityName);
		partyActivity.setActivityDate(activityDate);
		partyActivity.setActivityType(activityType);
		partyActivity.setAddress(address);
		partyActivity.setAttendNum(attendNum);
		partyActivity.setContent(content);
		partyActivity.setSituation(situation);
		// 保存上传的图片路径，图片路径之间用;间隔
		List<String> imgList = getImagePath();
		String pics = "";
		if(imgList != null && imgList.size() > 0){
			for(String img : imgList){
				pics += img + ";";
			}
			pics = pics.substring(0, pics.length() - 1);
		}
		partyActivity.setPics(pics);
//		Json json = new Json();
//		partyActivity.setCreateDate(new Date());
//		boolean result = partyActivityServ.updatePartyActivity(partyActivity);
//		if (result) {
//			json.setMessage("编辑成功");
//		} else {
//			json.setSuccess(true);
//			json.setMessage("编辑失败");
//		}
//		JsonUtil.writeJson(json);
		boolean result = partyActivityServ.updatePartyActivity(partyActivity);
		if (result) {
			flag = "编辑成功";
		} else {
			flag = "编辑失败";
		}
		
		if(editFrom == 1){
			partyActivity = new PartyActivity();
			return getPartyActivityListForPage();
		}else if(editFrom == 2){
			return toShowPartyActivity();
		}else{
			
		}
		
		partyActivity = new PartyActivity();
		return getPartyActivityListForPage();
	}
	
	/**
	 * 跳转到新增界面
	 * 
	 * @return
	 */
	public String toAddPartyActivity() {
		communityGeneralPartyList = communityGeneralPartyServ.getAllCommunityGeneralParty();
		communityPartyList = communityPartyServ.getAllCommunityParty();
		return "addPartyActivity.jsp";
	}
	
	/**
	 * 保存新增党建动态
	 */
	public String savePartyActivity() {
		partyActivity.setPartyType(partyType);
		partyActivity.setPartyName(partyName);
		partyActivity.setActivityName(activityName);
		partyActivity.setActivityDate(activityDate);
		partyActivity.setActivityType(activityType);
		partyActivity.setAddress(address);
		partyActivity.setAttendNum(attendNum);
		partyActivity.setContent(content);
		partyActivity.setSituation(situation);
		// 保存上传的图片路径，图片路径之间用;间隔
		List<String> imgList = getImagePath();
		String pics = "";
		if(imgList != null && imgList.size() > 0){
			for(String img : imgList){
				pics += img + ";";
			}
			pics = pics.substring(0, pics.length() - 1);
		}
		partyActivity.setPics(pics);
//		Json json = new Json();
//		boolean result = partyActivityServ.savePartyActivity(partyActivity);
//		if (result) {
//			json.setMessage("新增成功");
//		} else {
//			json.setSuccess(true);
//			json.setMessage("新增失败");
//		}
//		JsonUtil.writeJson(json);
		boolean result = partyActivityServ.savePartyActivity(partyActivity);
		if (result) {
			flag = "新增成功";
		} else {
			flag = "新增失败";
		}
		
		partyActivity = new PartyActivity();
		return getPartyActivityListForPage();
	}
	
	/**
	 * 删除党建动态
	 */
	public void delPartyActivity() {
		Json json = new Json();
		boolean result = partyActivityServ.delPartyActivity(partyActivity.getTimeKey());
		if (result) {
			json.setMessage("删除成功");
		} else {
			json.setSuccess(true);
			json.setMessage("删除失败");
		}
		JsonUtil.writeJson(json);
	}
	
	/**
	 * 显示详细信息
	 * @return
	 */
	public String toShowPartyActivity(){
		partyActivity = partyActivityServ.getPartyActivityById(partyActivity.getTimeKey());
		// 解析党建动态图片
		String picStr = partyActivity.getPics();
		if(!StringUtils.isBlank(picStr)){
			StringTokenizer st = new StringTokenizer(picStr, ";");
			picList = new ArrayList<String>();
			while(st.hasMoreElements()){
				picList.add(st.nextToken());
			}
		}
		
		return "showPartyActivity.jsp";
	}
	
	/**
	 * 导出党建动态到Excel
	 */
	public void exportPartyActivityListToExcel(){		
		// 解决中文乱码，通过指定的编码解密即可。
		try {
			String partyNameT;
			if(!StringUtils.isBlank(partyActivity.getPartyName())){
				partyNameT = URLDecoder.decode(partyActivity.getPartyName(), "utf-8");
			}else{
				partyNameT = "";
			}
			String activityNameT;
			if(!StringUtils.isBlank(partyActivity.getActivityName())){
				activityNameT = URLDecoder.decode(partyActivity.getActivityName(), "utf-8");
			}else{
				activityNameT = "";
			}
			String activityTypeT;
			if(!StringUtils.isBlank(partyActivity.getActivityType())){
				activityTypeT = URLDecoder.decode(partyActivity.getActivityType(), "utf-8");
			}else{
				activityTypeT = "";
			}
			String activityDateT;
			if(!StringUtils.isBlank(partyActivity.getActivityDate())){
				activityDateT = URLDecoder.decode(partyActivity.getActivityDate(), "utf-8");
			}else{
				activityDateT = "";
			}
			String addressT;
			if(!StringUtils.isBlank(partyActivity.getAddress())){
				addressT = URLDecoder.decode(partyActivity.getAddress(), "utf-8");
			}else{
				addressT = "";
			}
			Integer attendNumT;
			if(partyActivity.getAttendNum() != null){
				String attendNumStr = URLDecoder.decode(partyActivity.getAttendNum().toString(), "utf-8");
				attendNumT = Integer.valueOf(attendNumStr);
			}else{
				attendNumT = null;
			}
			String contentT;
			if(!StringUtils.isBlank(partyActivity.getContent())){
				contentT = URLDecoder.decode(partyActivity.getContent(), "utf-8");
			}else{
				contentT = "";
			}
			String situationT;
			if(!StringUtils.isBlank(partyActivity.getSituation())){
				situationT = URLDecoder.decode(partyActivity.getSituation(), "utf-8");
			}else{
				situationT = "";
			}
			partyActivity.setPartyName(partyNameT);
			partyActivity.setActivityName(activityNameT);
			partyActivity.setActivityType(activityTypeT);
			partyActivity.setActivityDate(activityDateT);
			partyActivity.setAddress(addressT);
			partyActivity.setAttendNum(attendNumT);
			partyActivity.setContent(contentT);
			partyActivity.setSituation(situationT);
			partyActivity.setPartyType(partyType);
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		List<PartyActivity> list = partyActivityServ.getPartyActivityList(partyActivity);
		if(list != null && list.size() > 0){
			List<ExcelPartyActivity> elist = new ArrayList<ExcelPartyActivity>();
			for(PartyActivity pActivity : list){
				ExcelPartyActivity epActivity = new ExcelPartyActivity();
				if(!StringUtils.isBlank(pActivity.getPartyName())){
					epActivity.setPartyName(pActivity.getPartyName());
				}else{
					epActivity.setPartyName("");
				}
				if(!StringUtils.isBlank(pActivity.getActivityName())){
					epActivity.setActivityName(pActivity.getActivityName());
				}else{
					epActivity.setActivityName("");
				}
				if(!StringUtils.isBlank(pActivity.getActivityType())){
					epActivity.setActivityType(pActivity.getActivityType());
				}else{
					epActivity.setActivityType("");
				}
				if(!StringUtils.isBlank(pActivity.getActivityDate())){
					epActivity.setActivityDate(pActivity.getActivityDate());
				}else{
					epActivity.setActivityDate("");
				}
				if(!StringUtils.isBlank(pActivity.getAddress())){
					epActivity.setAddress(pActivity.getAddress());
				}else{
					epActivity.setAddress("");
				}
				if(pActivity.getAttendNum() != null){
					epActivity.setAttendNum(pActivity.getAttendNum());
				}else{
					epActivity.setAttendNum(0);
				}
				if(!StringUtils.isBlank(pActivity.getContent())){
					String content = pActivity.getContent();
					content = RegExHtmlUtils.regEx_html(content);
					epActivity.setContent(content);
				}else{
					epActivity.setContent("");
				}
				if(!StringUtils.isBlank(pActivity.getSituation())){
					String situation = pActivity.getSituation();
					situation = RegExHtmlUtils.regEx_html(situation);
					epActivity.setSituation(situation);
				}else{
					epActivity.setSituation("");
				}
				elist.add(epActivity);
			}
			LinkedHashMap<String,String> fieldMap = new LinkedHashMap<String, String>();
			fieldMap.put("partyName", "党组织名称");
			fieldMap.put("activityName", "活动名称");
			fieldMap.put("activityType", "活动类型");
			fieldMap.put("activityDate", "活动日期");
			fieldMap.put("address", "活动地址");
			fieldMap.put("attendNum", "参加人数");
			fieldMap.put("content", "活动内容");
			fieldMap.put("situation", "活动情况");
			String sheetName = "居民区";
			HttpServletResponse response = ServletActionContext.getResponse();
			OutputStream out;
			try {
				out = response.getOutputStream();
				ExcelUtil.listToExcel(elist, fieldMap, sheetName, elist.size(), response, out);
			} catch (IOException | ExcelException e) {
				e.printStackTrace();
			}  	
		}
	}
	
	private List<String> getImagePath(){
		String fileDir = ServletActionContext.getServletContext().getRealPath("pics");
		File filePath = new File(fileDir);
		if(!filePath.exists()){
			filePath.mkdir();
		}
		List<String> slist = new ArrayList<String>();
		List<File> flist = getImage();
		if(flist!=null && flist.size()>0){
			for(int i=0;i<flist.size();i++){
				String geshi = imageFileName.get(i).substring(imageFileName.get(i).lastIndexOf("."));
				FileInputStream fi =null;
				FileOutputStream fo =null;
				String fileName="";
				try {
					fi = new FileInputStream(flist.get(i));
					File newFile = new File(filePath,System.nanoTime()+geshi);
					fo = new FileOutputStream(newFile);
					int length=0;
					byte[] bytes = new byte[2048];
					while((length=fi.read(bytes))>0){
						fo.write(bytes,0,length);
					}
					fileName =newFile.getName();
				} catch (Exception e) {
					e.printStackTrace();
				}finally{
					if(fi!=null){
						try {
							fi.close();
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
					if(fo!=null){
						try {
							fo.close();
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				}
				slist.add(fileName);
			}
		}
		return slist;
	}
}
